package df.bean.process;

import java.util.ArrayList;
import java.util.HashMap;

import df.bean.db.conn.DBConn;
import df.bean.db.conn.DBConnection;
import df.bean.db.table.PaymentMonthly;
import df.bean.db.table.StpMethodAllocPayor;
import df.bean.db.table.TRN_Error;
import df.bean.db.table.TrnDaily;
import df.bean.obj.Item.DrMethodAllocation;
import df.bean.obj.doctor.CareProvider;
import df.bean.obj.doctor.DoctorList;
import df.bean.obj.util.FindQueryData;
import df.bean.obj.util.JDate;
import df.bean.obj.util.AjaxUtils;


public class ProcessAjaxCalculate extends ProcessTransDaily{
	private DoctorList drList  = null;
	private HashMap<String, String> hashData  = new HashMap<String, String>();
    private DrMethodAllocation drMethodAllocation =null;
    private DBConnection connect = null;
    private PaymentMonthly pm = null;
    private StpMethodAllocPayor methodAllocctionPayor = null;

	public AjaxUtils getInvoice(String startDate,String endDate,String hospitalCode){
		AjaxUtils process = new AjaxUtils();
		process.setHospitalCode(hospitalCode);
		
		DBConn dbConn = new DBConn();
		DBConnection conn = new DBConnection();
		FindQueryData findQueryData = new FindQueryData();
		String replaceStartDeta = JDate.saveDate(startDate);
		String replaceEndDate = JDate.saveDate(endDate);
        String lstCode ="";
        boolean checkProcessDaily = true;
        ArrayList<String> arrlstCode = new ArrayList<String>();
        int countFail = 0 ;
        
        if(conn.connectToLocal()){
            this.drList = new DoctorList(hospitalCode, conn);
            this.connect = conn; 
        }
        
        String sql = "SELECT DISTINCT INVOICE_NO "+
        			" FROM TRN_DAILY " +
                    " WHERE HOSPITAL_CODE = '" + hospitalCode + "'" +
                    " AND (TRANSACTION_DATE >= '" + replaceStartDeta + "'" +     // #20071123# this.getStartComputeDate()
                    " AND TRANSACTION_DATE <= '" + replaceEndDate + "')" +  // #20071123# this.getEndComputeDate()
                    " AND (BATCH_NO IS NULL OR BATCH_NO = '')" +
                    " AND ACTIVE = '1' " +
                    " AND AMOUNT_AFT_DISCOUNT <> 0 " +
                    " AND (COMPUTE_DAILY_DATE IS NULL OR COMPUTE_DAILY_DATE = '') ";
        sql = sql + " ORDER BY INVOICE_NO";
        System.out.println("cal : "+sql);
        ArrayList<HashMap<String, String>> arrData = dbConn.listQueryData(sql);

        drList.newAllDoctor(hospitalCode);
        drMethodAllocation = new DrMethodAllocation(conn, hospitalCode);
        this.methodAllocctionPayor = new StpMethodAllocPayor(hospitalCode, this.connect);

        if(arrData.size() > 0){
	        for (int j=0; j<arrData.size(); j++) {
	            HashMap<String, String> hashData = arrData.get(j);
	            lstCode = hashData.get("INVOICE_NO");
	            
	            int numAffRec = 0;
	            setDoctorList(drList);
	            setDrMedthodAlloction(drMethodAllocation);
	            setDrMedthodPayorAlloction(this.methodAllocctionPayor);
	            if (processCalculate(replaceStartDeta, replaceEndDate, hospitalCode, lstCode,process)) {
	                numAffRec = 1;
	                checkProcessDaily = true;
	            }else {
	                numAffRec = 0;
	            }
        	}
        }else{ 
        	System.out.println("Not Found Data");
            checkProcessDaily = false;
        }
        process.setArrData(arrlstCode);
        process.setCheck(checkProcessDaily);
        process.setCount(countFail);
        conn.Close();
        return process;
	}
	public boolean processCalculate(String startDate, String endDate, String hospitalCode, String invoiceNo,AjaxUtils process) {
	        boolean ret = false;
	        String doctorCode = "";
	        CareProvider careProvider = null;
			DBConnection conn = new DBConnection();
			TrnDaily tDaily = null;
			String errorMessage = "";
			ArrayList<String> arrErrorMessage = new ArrayList<String>();
		    
		        if (drMethodAllocation == null){
		        	drMethodAllocation = new DrMethodAllocation(this.getDBConnection(), hospitalCode); 
		        }
	        	tDaily = new TrnDaily(this.connect);
	            try {
	                ret = true;
	                String sql = TrnDaily.getSQL_TRN_DAILY(startDate, endDate, hospitalCode, invoiceNo);
	                tDaily.OpenResultSet(sql);
	            	
	                while (tDaily.MoveNext()) {
	                                        
	                    doctorCode = tDaily.getDoctorCode();
	                    careProvider = this.getDoctorList().getDoctor(doctorCode);
	                    if (careProvider != null) {
	                        careProvider.setTrnDaily(tDaily);
	                        careProvider.setDrMethodAllocation(this.drMethodAllocation);
	                        careProvider.setDrMethodPayorAllocation(this.methodAllocctionPayor);
	                        if (careProvider.computeTransDaily()) { 
	                            ret = true;
	                        } 
	                        else {  
	                            ret = false;
	                            errorMessage = "Error";
//	                            break;   
	                        }
	                    } else {
	                        ret = false;
	                        errorMessage = "Doctor Code : " + doctorCode + " is not found.";
//	                        break;
	                    }
	                    if(!errorMessage.equals("")){
	                    	arrErrorMessage.add(errorMessage);
	                    	process.setErrorMessage(arrErrorMessage);
	                    }
	                }
//	                if (ret) { this.getDBConnection().commitTrans(); }
//	                if (!ret) { this.getDBConnection().rollBackTrans(); }
//	                if (ret) { ret = tDaily.updateCompute(startDate, endDate, hospitalCode, invoiceNo, lineNo); }
	            } catch (Exception e) {
	                // TODO
	                e.printStackTrace();
	                TRN_Error.writeErrorLog(this.getConn().getConnection(), TRN_Error.PROCESS_DAILY, "", e.getMessage());
	                ret=false;
	            } finally {
	               //Clean up resources, close the connection.
	                try {
	                    tDaily.setStatement(null);
	                    tDaily.setResultSet(null);
	                    tDaily = null;
	                    conn.Close();
	                } catch (Exception ex) { 
	                    ex.printStackTrace();  
	                    TRN_Error.writeErrorLog(this.getConn().getConnection(), TRN_Error.PROCESS_DAILY, "", ex.getMessage());
	                    ret = false; 
	                } 
	            }
	        
	        return ret;
	    }
	public AjaxUtils getDrGuanateeByIsGuanateeProfire(String hospitalCode, String doctorProfileCode,String guaranteeProfile,String columnName){
		AjaxUtils process = new AjaxUtils();
		
		DBConn dbConn = new DBConn();
		DBConnection conn = new DBConnection();
		ArrayList<String> arrData = new ArrayList<String>();
		String sql = "";
        
        if(conn.connectToLocal()){
            this.connect = conn; 
        }
        
        //System.out.println("columnName = " + columnName);
        
        sql = "SELECT CODE FROM DOCTOR WHERE HOSPITAL_CODE = '"+hospitalCode+"'";
        if(guaranteeProfile.equals("Y")){
        	sql += " AND DOCTOR_PROFILE_CODE = '"+doctorProfileCode+"'";
        	arrData = dbConn.getSingleDataIsArrayList(sql,columnName);
        	//System.out.println("sql = " + sql);
        	if(arrData.size()>0){
                process.setCode(arrData.get(1));
        	}else{
        		process.setCode("");
        	}
        }else{
        	arrData = dbConn.getSingleDataIsArrayList(sql, columnName);
        }
        process.setArrData(arrData);
		return process;
		
	}
	//Monthly Process
	public AjaxUtils insertDataByCode(String hospitalCode, String MM, String YYYY) {
		
		AjaxUtils ajaxUtilForm = new AjaxUtils();
		DBConnection conn = new DBConnection();
		boolean ret = true;
		String sql = "";	
		DBConn dbConn = new DBConn();
		HashMap<String, String> hashData = new HashMap<String, String>();
		ArrayList<Boolean> arrBoolean = new ArrayList<Boolean>();
        
        if(conn.connectToLocal()){
            this.connect = conn; 
        }
        drList = new DoctorList(hospitalCode, conn);
        drList.newAllDoctor(hospitalCode);
        
        sql="SELECT CODE FROM DOCTOR WHERE HOSPITAL_CODE = '"+hospitalCode+"'";
        ArrayList<HashMap<String, String>> arrData = dbConn.listQueryData(dbConn.getConnection(), sql);
        //System.out.println("Size of list : "+arrData.size());
        setDoctorList(drList);
        for(int i=0;i<arrData.size();i++){
        	hashData = arrData.get(i);
        	//System.out.println(hashData.get("CODE")+"<>"+sql);
        	if (!Calculate(YYYY, MM, hospitalCode, hashData.get("CODE"),this.connect)) {
            	ret = false;
        	}else{
        		ret = true;
        	}
        }
        ajaxUtilForm.setCount(arrData.size());
        ajaxUtilForm.setCheck(ret);
		return ajaxUtilForm;
	}
    public boolean Calculate(String YYYY, String MM, String hospitalCode, String doctorCode, DBConnection conn) {
        boolean ret = true;
        CareProvider careProvider = null;
        careProvider = this.getDoctorList().getDoctor(doctorCode);
        //System.out.println("Monthly Process : "+this.getDoctorList().getDoctor(doctorCode).getDoctorCode()+" from param : "+doctorCode);
        if (careProvider != null) {
            careProvider.setDBConnection(conn);
            if (careProvider.computeTransMonthly()) {
                ret = true;    
            } 
            else {
                ret = false;   
            }
        }

        return ret;
    }
    //End Monthly Process
    
    //Payment Summary
    public AjaxUtils paymentSummury(String hospitalCode, String date){
    	AjaxUtils ajaxUtilForm = new AjaxUtils();
		boolean check = true;
		DBConn dbConn = new DBConn();
		String sql = "";
		HashMap<String, String> hashData = new HashMap<String, String>();
        sql="SELECT CODE FROM DOCTOR WHERE HOSPITAL_CODE = '"+hospitalCode+"'";
        ArrayList<HashMap<String, String>> arrData = dbConn.listQueryData(dbConn.getConnection(), sql);
        dbConn.closeDB("");
		this.connect = new DBConnection();
        this.connect.connectToLocal();
        if(arrData.size() > 0){
        	for(int i=0;i<arrData.size();i++){
            	System.out.println("Test");
        		hashData = arrData.get(i);
                if (!Calculate(hospitalCode, hashData.get("CODE"), JDate.saveDate(date))) {
                	check = false;
                }else{
                	check = true;
                }
        	}
        }else{
        	System.out.println("Data Not Found");
        }
        this.connect.Close();
        ajaxUtilForm.setCount(arrData.size());
        ajaxUtilForm.setCheck(check);
		return ajaxUtilForm;
    }
    public boolean Calculate(String hospitalCode, String doctorCode, String payDate) {
        boolean ret = false;
        pm = new PaymentMonthly(this.connect);
        if (pm.insertToPaymentSummmary(hospitalCode, payDate, doctorCode)>-1) {
            ret = true;    
        }else {  
            ret = false;   
        }
        return ret;
    } 
    //End Paymeny Summnry
	public String getInterfaceName(){
		return "ProcessDaily";
	}
}
